<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @open="dialogOpen" @close="closeDialog">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="isLoading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="confirmAddRole">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserInfoAPI } from '@/api/user'
import { assignRolesApi } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleIds: [],
      roleList: [],
      isLoading: false
    }
  },
  methods: {
    async confirmAddRole() {
      await assignRolesApi({ id: this.userId, roleIds: this.roleIds })
      // this.$message.success('员工角色分配成功')
      this.closeDialog()
    },
    // 弹框出现
    dialogOpen() {
      this.isLoading = true
      // await this.getRoleList()
      // await this.getUserInfo()
      Promise.all([this.getRoleList(), this.getUserInfo()]).then(() => {
        this.isLoading = false
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.$parent.showRoleDialog = false
    },
    // 获取角色列表
    async getRoleList() {
      const {
        data: { rows }
      } = await getRoleListApi(1, 9999)
      this.roleList = rows
    },
    async getUserInfo() {
      const { data: { roleIds }} = await getUserInfoAPI(this.userId)
      this.roleIds = roleIds || []
    }
  }
}
</script>
